<template>
    <view class="address-form-container">
        <!-- 顶部导航栏 -->
        <view class="header">
            <view class="back-button" @click="goBack">
            </view>
            <view class="page-title">{{ isEdit ? '编辑地址' : '添加地址' }}</view>
            <view class="placeholder"></view>
        </view>

        <!-- 表单区域 -->
        <view class="form-section">
            <!-- 联系人 -->
            <view class="form-item">
                <view class="form-label">联系人</view>
                <input class="form-input" v-model="formData.name" placeholder="请输入姓名" />
            </view>

            <!-- 手机号码 -->
            <view class="form-item">
                <view class="form-label">手机号码</view>
                <input class="form-input" v-model="formData.phone" placeholder="请输入手机号码" type="number" maxlength="11" />
            </view>

            <!-- 地区选择 -->
            <view class="form-item">
                <view class="form-label">所在地区</view>
                <picker mode="region" @change="onRegionChange" :value="formData.region">
                    <view class="region-picker">
                        <text class="region-text">{{ formData.region[0] }} {{ formData.region[1] }} {{
                            formData.region[2] }}</text>
                        <text class="iconfont icon-arrow"
                            :style="{ color: theme.textLightGray, fontSize: '24rpx' }"></text>
                    </view>
                </picker>
            </view>

            <!-- 详细地址 -->
            <view class="form-item">
                <view class="form-label">详细地址</view>
                <textarea class="form-textarea" v-model="formData.addressDetail"
                    placeholder="请输入详细地址，如街道、门牌号、小区、楼栋号、单元室等信息"></textarea>
            </view>

            <!-- 设为默认地址 -->
            <view class="form-item switch-item">
                <view class="form-label">设为默认地址</view>
                <switch class="form-switch" :checked="formData.isDefault" @change="onDefaultChange"
                    :style="{ color: switchColor }" />
            </view>
        </view>

        <!-- 删除按钮 -->
        <view class="delete-button" v-if="isEdit" @click="deleteAddress">删除此地址</view>

        <!-- 保存按钮 -->
        <view class="save-button" @click="saveAddress">保存</view>
    </view>
</template>

<script>
import theme from '@/utils/theme.js';
import Icon from '@/components/common/Icon.vue';

export default {
    components: {
        Icon
    },
    data() {
        return {
            isEdit: false,
            addressId: null,
            formData: {
                name: '',
                phone: '',
                region: ['北京市', '北京市', '朝阳区'],
                addressDetail: '',
                isDefault: false
            },
            // 从主题工具类引入的颜色值
            switchColor: '',
            theme
        };
    },
    created() {
        // 设置开关按钮的颜色
        this.switchColor = theme.primaryGreen;
    },
    methods: {
        // 返回上一页
        goBack() {
            uni.navigateBack();
        },

        // 地区选择
        onRegionChange(e) {
            this.formData.region = e.detail.value;
        },

        // 设置默认地址
        onDefaultChange(e) {
            this.formData.isDefault = e.detail.value;
        },

        // 保存地址
        saveAddress() {
            // 表单验证
            if (!this.formData.name) {
                uni.showToast({
                    title: '请输入联系人',
                    icon: 'none'
                });
                return;
            }

            if (!this.formData.phone) {
                uni.showToast({
                    title: '请输入手机号码',
                    icon: 'none'
                });
                return;
            }

            // 验证手机号格式
            if (!/^1\d{10}$/.test(this.formData.phone)) {
                uni.showToast({
                    title: '手机号格式不正确',
                    icon: 'none'
                });
                return;
            }

            if (!this.formData.addressDetail) {
                uni.showToast({
                    title: '请输入详细地址',
                    icon: 'none'
                });
                return;
            }

            // 构建完整地址字符串
            const fullAddress = this.formData.region.join('') + ' ' + this.formData.addressDetail;

            // 构建提交数据
            const addressData = {
                id: this.isEdit ? this.addressId : new Date().getTime(),
                name: this.formData.name,
                phone: this.formData.phone,
                detail: fullAddress,
                isDefault: this.formData.isDefault
            };

            console.log('提交地址数据：', addressData);

            // 保存地址到本地存储
            this.saveAddressToStorage(addressData);
        },

        // 保存地址到本地存储
        saveAddressToStorage(newAddress) {
            uni.showLoading({
                title: '保存中...'
            });

            // 从本地存储获取地址列表
            uni.getStorage({
                key: 'addressList',
                success: (res) => {
                    let addressList = res.data || [];

                    // 如果设置为默认地址，则将其他地址的默认状态取消
                    if (newAddress.isDefault) {
                        addressList = addressList.map(item => {
                            if (item.id !== newAddress.id) {
                                return { ...item, isDefault: false };
                            }
                            return item;
                        });
                    }

                    // 如果是编辑模式，则更新对应的地址
                    if (this.isEdit) {
                        const index = addressList.findIndex(item => item.id === newAddress.id);
                        if (index !== -1) {
                            addressList[index] = newAddress;
                        }
                    } else {
                        // 否则添加新地址
                        addressList.push(newAddress);
                    }

                    // 保存到本地存储
                    this.updateAddressStorage(addressList);
                },
                fail: () => {
                    // 如果本地没有存储，则创建新的地址列表
                    const addressList = [newAddress];
                    this.updateAddressStorage(addressList);
                }
            });
        },

        // 更新地址列表存储
        updateAddressStorage(addressList) {
            uni.setStorage({
                key: 'addressList',
                data: addressList,
                success: () => {
                    uni.hideLoading();
                    uni.showToast({
                        title: this.isEdit ? '修改成功' : '添加成功',
                        icon: 'success'
                    });

                    setTimeout(() => {
                        uni.navigateBack();
                    }, 1500);
                },
                fail: () => {
                    uni.hideLoading();
                    uni.showToast({
                        title: '保存失败',
                        icon: 'none'
                    });
                }
            });
        },

        // 删除地址
        deleteAddress() {
            uni.showModal({
                title: '提示',
                content: '确定要删除该地址吗？',
                success: (res) => {
                    if (res.confirm) {
                        uni.showLoading({
                            title: '删除中...'
                        });

                        // 从本地存储获取地址列表并删除对应的地址
                        uni.getStorage({
                            key: 'addressList',
                            success: (res) => {
                                let addressList = res.data || [];
                                addressList = addressList.filter(item => item.id !== this.addressId);

                                // 保存更新后的地址列表
                                uni.setStorage({
                                    key: 'addressList',
                                    data: addressList,
                                    success: () => {
                                        uni.hideLoading();
                                        uni.showToast({
                                            title: '删除成功',
                                            icon: 'success'
                                        });

                                        setTimeout(() => {
                                            uni.navigateBack();
                                        }, 1500);
                                    }
                                });
                            },
                            fail: () => {
                                uni.hideLoading();
                                uni.showToast({
                                    title: '删除失败',
                                    icon: 'none'
                                });
                            }
                        });
                    }
                }
            });
        },

        // 获取地址详情
        getAddressDetail(id) {
            // 从本地存储获取地址列表，并查找对应的地址
            uni.getStorage({
                key: 'addressList',
                success: (res) => {
                    const addressList = res.data || [];
                    const address = addressList.find(item => item.id === id);

                    if (address) {
                        // 解析完整地址，提取省市区和详细地址
                        let region = ['北京市', '北京市', '朝阳区']; // 默认值
                        let addressDetail = '';

                        // 尝试解析完整地址，提取省市区
                        const fullAddress = address.detail;
                        const provinceMatch = fullAddress.match(/^(.*?省|.*?市)/);
                        const cityMatch = fullAddress.match(/省(.*?市)|^(北京市|上海市|天津市|重庆市)/);
                        const districtMatch = fullAddress.match(/市(.*?区|.*?县|.*?市)/);

                        if (provinceMatch && cityMatch && districtMatch) {
                            region = [
                                provinceMatch[0],
                                cityMatch[0].replace(/省/, ''),
                                districtMatch[0].replace(/市/, '')
                            ];

                            // 提取详细地址（除去省市区的部分）
                            addressDetail = fullAddress.replace(region.join(''), '').trim();
                        } else {
                            // 如果无法解析，则直接使用完整地址作为详细地址
                            addressDetail = fullAddress;
                        }

                        // 设置表单数据
                        this.formData = {
                            name: address.name,
                            phone: address.phone,
                            region: region,
                            addressDetail: addressDetail,
                            isDefault: address.isDefault
                        };
                    } else {
                        uni.showToast({
                            title: '未找到地址信息',
                            icon: 'none'
                        });
                        setTimeout(() => {
                            uni.navigateBack();
                        }, 1500);
                    }
                },
                fail: () => {
                    uni.showToast({
                        title: '获取地址信息失败',
                        icon: 'none'
                    });
                    setTimeout(() => {
                        uni.navigateBack();
                    }, 1500);
                }
            });
        }
    },
    onLoad(options) {
        if (options.id) {
            this.isEdit = true;
            this.addressId = parseInt(options.id);
            this.getAddressDetail(this.addressId);
        }
    }
};
</script>

<style lang="scss">
@import '@/styles/global.scss';

.address-form-container {
    min-height: 100vh;
    background-color: $bg-color;
    padding-bottom: 120rpx;
}

/* 头部导航 */
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    background-color: $card-bg;
    position: relative;

    .back-button {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .page-title {
        font-size: 36rpx;
        font-weight: bold;
    }

    .placeholder {
        width: 60rpx;
    }
}

/* 表单区域 */
.form-section {
    background-color: $card-bg;
    margin-top: 20rpx;
}

.form-item {
    padding: 30rpx;
    border-bottom: 1rpx solid $border-color;
    display: flex;
    align-items: center;

    .form-label {
        width: 180rpx;
        font-size: 28rpx;
        color: $text-black;
    }

    .form-input {
        flex: 1;
        font-size: 28rpx;
    }

    .form-textarea {
        flex: 1;
        height: 160rpx;
        font-size: 28rpx;
    }

    .region-picker {
        flex: 1;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .region-text {
            font-size: 28rpx;
        }
    }
}

.switch-item {
    justify-content: space-between;
}

/* 删除按钮 */
.delete-button {
    margin: 30rpx;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 44rpx;
    text-align: center;
    background-color: $card-bg;
    color: $status-processing-text;
    font-size: 32rpx;
    border: 1rpx solid $border-color;
}

/* 保存按钮 */
.save-button {
    position: fixed;
    bottom: 30rpx;
    left: 30rpx;
    right: 30rpx;
    background-color: $primary-green;
    color: $text-white;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 44rpx;
    text-align: center;
    font-size: 32rpx;
}
</style>